package com.jxauaia.contest.controller;

import com.jxauaia.contest.common.response.Result;
import com.jxauaia.contest.model.dto.LoginDTO;
import com.jxauaia.contest.model.dto.RegisterDTO;
import com.jxauaia.contest.model.entity.User;
import com.jxauaia.contest.model.vo.CaptchaVO;
import com.jxauaia.contest.security.JwtTokenProvider;
import com.jxauaia.contest.service.CaptchaService;
import com.jxauaia.contest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {

    private final UserService userService;
    private final JwtTokenProvider jwtTokenProvider;

    @Autowired
    public AuthController(UserService userService, JwtTokenProvider jwtTokenProvider) {
        this.userService = userService;
        this.jwtTokenProvider = jwtTokenProvider;
    }

    /**
     * 获取验证码
     */
    @GetMapping("/captcha")
    public Result<CaptchaVO> getCaptcha() {
        CaptchaVO captchaVO = userService.generateCaptcha();
        return Result.success(captchaVO);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody @Validated RegisterDTO registerDTO) {
        // 验证用户名和邮箱是否已存在
        if (userService.existsByUsername(registerDTO.getUsername())) {
            return Result.error(400, "用户名已存在");
        }
        if (userService.existsByEmail(registerDTO.getEmail())) {
            return Result.error(400, "邮箱已被注册");
        }

        // 注册用户
        User user = userService.register(registerDTO);
        return Result.success("注册成功", user);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody @Validated LoginDTO loginDTO) {
        User user = userService.login(loginDTO);

        // 生成JWT令牌
        String token = jwtTokenProvider.generateToken(user.getUsername());

        // 构建返回数据
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", user);

        return Result.success("登录成功", data);
    }

    /**
     * 验证用户名是否可用
     */
    @GetMapping("/check-username")
    public Result<Boolean> checkUsername(@RequestParam String username) {
        User user = userService.findByUsername(username);
        return Result.success(user == null);
    }

    /**
     * 验证邮箱是否可用
     */
    @GetMapping("/check-email")
    public Result<Boolean> checkEmail(@RequestParam String email) {
        User user = userService.findByEmail(email);
        return Result.success(user == null);
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<Boolean> logout(HttpServletRequest request) {
        // 获取Authorization头
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            // 将token加入黑名单（需要实现TokenBlacklistService）
            // tokenBlacklistService.addToBlacklist(token);

            // 如果没有实现token黑名单，可以简单返回成功
            return Result.success("退出登录成功", true);
        }
        return Result.error(400, "退出失败，未找到有效token");
    }
}